//
//  MBDModifyUserInfoViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/25.
//

import Foundation

import UIKit
import YYText
import SnapKit
import Alamofire
import SwiftyJSON
import Toast_Swift
import MJRefresh

// 定义枚举
enum MBDModyfiyInfoType {
    case nickName
    case wechatNum
}

class MBDModifyUserInfoViewModel : MBDModifyInfoViewModel {
    var modifyInfoType : MBDModyfiyInfoType!
    
    init(editType: MBDModyfiyType = .textField, placeHolder: String = "", title: String = "",modifyInfoType: MBDModyfiyInfoType = .nickName) {
        super.init(editType: editType,placeHolder: placeHolder,title: title)
        self.modifyInfoType = modifyInfoType
    }
    
    
    func doRequest(info: String, type : MBDModyfiyInfoType = .nickName,completion : @escaping ( _ error : NSError?,_ result : Bool)->()) {
        
        if let current = MBDAccountInfoModel.current() {
            var params : Dictionary<String, Any>
            if type == .nickName {
                params = ["userId":String(current.userId),"realName": info]
            } else if type == .wechatNum {
                params = ["userId":String(current.userId),"weChatNumber": info]
            } else {
                params = ["userId":String(current.userId)]
            }
            
            MBDHttpClient.shared.request("/user/update",method: .put,parameters: params,encoding: JSONEncoding.default).httpClientResponse { error, response in
                if nil != error {
                    completion(error!,false)
                } else {
                    let rawDict = response?.rawDict!
                    completion(nil,true)
                }                
            }
        }
    }    
}


class MBDModifyUserInfoViewController : MBDModifyInfoViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
     
    @objc override func rightItemPressed(){
        let cellModel = self.viewModel.cellModels.first as! MBDModifyInfoBaseCellModel
        let viewModel = self.viewModel as! MBDModifyUserInfoViewModel
        
        viewModel.doRequest(info: cellModel.text!,type: viewModel.modifyInfoType) { error,result in
            if nil != error {
                self.view.makeToast(error?.localizedDescription)
            } else {
                MBDAccountInfoModel.current()?.update(notify: true)
                
                self.navigationController?.popViewController(animated: true)
            }
            
        }
        
    }
    
}
